<template>
  <div id="home">
    <el-row>
      <el-col :span="24">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户与权限</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24" align="right">
        <el-button @click="clearFilter" size="small">
          清除所有筛选
          <i class="el-icon-close el-icon--right"></i>
        </el-button>
        <el-button
          @click="handleAddUser"
          size="small"
          type="success"
          icon="el-icon-circle-plus-outline"
        >添加用户</el-button>
      </el-col>
    </el-row>
    <br>
    <el-row>
      <el-col :span="24">
        <el-table
          ref="tableUser"
          :data="tableUserData"
          border
          stripe
          fit
          highlight-current-row
          v-loading="tableUserLoading"
          max-height="1200"
        >
          <el-table-column type="index" label="序号" :index="indexMethod" width="80"></el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="phone" label="手机号码" width="120"></el-table-column>
          <el-table-column prop="email" label="Email" width="240"></el-table-column>
          <el-table-column prop="created" label="创建日期" :formatter="dateFormat" width="180" sortable></el-table-column>
          <el-table-column prop="updated" label="修改日期" :formatter="dateFormat" width="180" sortable></el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="80"
            :filters="[{ text: '正常', value: 1 }, { text: '禁用', value: 2 }]"
            :filter-method="filterStatus"
            filter-placement="bottom-end"
          >
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === 1 ? 'success' : 'danger'"
                size="small"
                disable-transitions
              >{{scope.row.status === 1 ? '正常' : '禁用'}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                @click="handleEditUser(scope.$index, scope.row)"
                type="text"
                size="small"
              >编辑</el-button>
              <el-button
                @click="handleResetPwd(scope.$index, scope.row)"
                type="text"
                size="small"
              >重置密码</el-button>
              <el-button
                @click="handleSetRole(scope.$index, scope.row)"
                type="text"
                size="small"
              >指定角色</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[1, 10, 20, 50, 100]"
          :page-size="20"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-col>
    </el-row>

    <el-dialog
      :title="dialogUserTitle"
      :visible.sync="dialogUserVisible"
      width="600px"
      @closed="dialogUserClosed"
    >
      <el-form ref="formUser" :model="modelUser" status-icon :rules="rulesUser">
        <el-form-item label="用户名" :label-width="formUserLabelWidth" prop="username">
          <el-input v-model="modelUser.username" autocomplete="off" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formUserLabelWidth" prop="phone">
          <el-input v-model="modelUser.phone" autocomplete="off" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="Email" :label-width="formUserLabelWidth" prop="email">
          <el-input v-model="modelUser.email" autocomplete="off" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formUserLabelWidth">
          <el-select v-model="modelUser.status" placeholder="请选择状态">
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserVisible = false">取 消</el-button>
        <el-button type="primary" :loading="isButtonLoadingUser" @click="onSubmitUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="dialogSetRoleTitle"
      :visible.sync="dialogSetRoleVisible"
      width="600px"
      @closed="dialogSetRoleClosed"
    >
      <el-transfer v-model="valueSetRole" :data="dataSetRole" :titles="titlesSetRole"></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSetRoleVisible = false">取 消</el-button>
        <el-button type="primary" :loading="isButtonLoadingSetRole" @click="onSubmitSetRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAPI } from '../assets/js/resources.js'
import { formatDate } from '../assets/js/nix.utils.js'
var Qs = require('qs')

export default {
  name: 'Home',
  data() {
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      } else {
        callback()
      }
    }
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else {
        callback()
      }
    }
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('Email不能为空'))
      } else {
        callback()
      }
    }
    return {
      page: 1,
      rows: 20,
      total: 100,
      tableUserData: [],
      tableUserLoading: false,
      dialogUserVisible: false,
      dialogUserTitle: '添加用户',
      statusOptions: [
        {
          label: '正常',
          value: 1
        },
        {
          label: '禁用',
          value: 2
        }
      ],
      modelUser: {
        id: null,
        username: '',
        phone: '',
        email: '',
        status: 1
      },
      rulesUser: {
        username: [{ validator: checkUsername, trigger: 'blur' }],
        phone: [{ validator: checkPhone, trigger: 'blur' }],
        email: [{ validator: checkEmail, trigger: 'blur' }]
      },
      formUserLabelWidth: '60px',
      isButtonLoadingUser: false,
      dataSetRole: [],
      valueSetRole: [],
      userIdSetRole: null,
      dialogSetRoleTitle: '指定角色',
      dialogSetRoleVisible: false,
      isButtonLoadingSetRole: false,
      titlesSetRole: ['未指定角色', '已指定角色']
    }
  },
  methods: {
    /* Table */
    loadTableUserData() {
      this.tableUserLoading = true
      var that = this
      this.$axios
        .get(getAPI('API_GET_USER_LIST'), {
          params: { page: that.page, rows: that.rows }
        })
        .then(function(response) {
          if (response.data.status === 200) {
            that.tableUserData = response.data.data.list
            that.total = response.data.data.total
            that.tableUserLoading = false
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    handleSizeChange(val) {
      // console.log('每页' + val + '条');
      this.rows = val
      this.loadTableUserData()
    },
    handleCurrentChange(val) {
      // console.log('当前页:' + val);
      this.page = val
      this.loadTableUserData()
    },
    handleAddUser() {
      this.dialogUserTitle = '添加用户'
      this.dialogUserVisible = true
    },
    handleEditUser(index, row) {
      // console.log(index, row);
      // this.$message(row.id + '');
      this.dialogUserTitle = '修改用户'
      this.dialogUserVisible = true
      this.modelUser.id = row.id
      this.modelUser.username = row.username
      this.modelUser.phone = row.phone
      this.modelUser.email = row.email
      this.modelUser.status = row.status
    },
    handleResetPwd(index, row) {
      this.$confirm('确认要重置用户【' + row.username + '】的密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var that = this
        this.$axios({
          method: 'post',
          url: getAPI('API_POST_USER_RESET_PWD') + row.id,
          // 序列化为&格式
          data: Qs.stringify(that.modelUser)
        })
          .then(function(response) {
            if (response.data.status === 200) {
              that.$message({
                message: '保存成功',
                type: 'success'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      })
    },
    indexMethod(index) {
      return index + 1
    },
    dateFormat(row, column, cellValue, index) {
      var date = new Date(cellValue)
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    },
    filterStatus(value, row) {
      return row.status === value
    },
    clearFilter() {
      this.$refs.tableUser.clearFilter()
    },
    /* Edit */
    onSubmitUser() {
      this.isButtonLoadingUser = true
      this.$refs.formUser.validate(valid => {
        if (valid) {
          var that = this
          this.$axios({
            method: 'post',
            url: getAPI('API_POST_USER_SAVE'),
            // 序列化为&格式
            data: Qs.stringify(that.modelUser)
          })
            .then(function(response) {
              if (response.data.status === 200) {
                that.$message({
                  message: '保存成功',
                  type: 'success'
                })
                that.isButtonLoadingUser = false
                that.dialogUserVisible = false
                that.loadTableUserData()
              } else {
                that.$message.error(response.data.msg)
                that.isButtonLoadingUser = false
              }
            })
            .catch(function(error) {
              console.log(error)
            })
        }
      })
    },
    resetForm() {
      this.modelUser = {
        id: null,
        username: '',
        phone: '',
        email: '',
        status: 1
      }
      this.$refs.formUser.resetFields()
    },
    dialogUserClosed() {
      this.resetForm()
    },
    /* Role */
    dialogSetRoleClosed() {
      this.valueSetRole = []
    },
    handleSetRole(index, row) {
      this.dialogSetRoleTitle = '为用户【' + row.username + '】指定角色'
      this.userIdSetRole = row.id
      var that = this
      this.$axios
        .get(getAPI('API_GET_USER_ROLE') + row.id)
        .then(function(response) {
          if (response.data.status === 200) {
            that.dialogSetRoleVisible = true
            that.valueSetRole = response.data.data
          } else {
            that.$message.error(response.data.msg)
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    onSubmitSetRole() {
      this.isButtonLoadingSetRole = true
      var that = this
      this.$axios({
        method: 'post',
        url: getAPI('API_POST_USER_SET_ROLE'),
        // 序列化为&格式
        data: Qs.stringify({
          userId: that.userIdSetRole,
          roleIds: that.valueSetRole.join(',')
        })
      })
        .then(function(response) {
          if (response.data.status === 200) {
            that.isButtonLoadingSetRole = false
            that.dialogSetRoleVisible = false
          } else {
            that.$message.error(response.data.msg)
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    loadDataSetRole() {
      var that = this
      this.$axios
        .get(getAPI('API_GET_ROLE_LIST'))
        .then(function(response) {
          if (response.data.status === 200) {
            var array = []
            response.data.data.list.forEach(function(item, index) {
              array.push({ key: item.id, label: item.name })
            })
            that.dataSetRole = array
          } else {
            that.$message.error(response.data.msg)
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    }
  },
  created() {
    this.loadTableUserData()
    this.loadDataSetRole()
  }
}
</script>

<style scoped>
</style>
